import HttpClient from '../commons/http-client';
import {updateAccountList} from '../reducers/account-list';
import {updateAccountDetail} from '../reducers/account-detail';

export function loadAccountList(payload) {
  return async dispatch => {
    const info = {
      page: payload.page,
      page_size: 10,
      expand: 'role',
    };
    const url = `/admin/master?${HttpClient.encodeParams(info)}`;
    const accountListRep = await HttpClient.get(url);
    dispatch(updateAccountList(accountListRep.data.data));
  };
}

export function loadRoleList() {
  return async dispatch => {
    const info = {
      expand: 'perms',
    };
    const roleListRep = await HttpClient.get(
      `/admin/role?${HttpClient.encodeParams(info)}`,
    );
    dispatch(updateAccountList({roleList: roleListRep.data.data.results}));
  };
}

export function newAccount(payload) {
  return async dispatch => {
    const roleInfo = {
      password: payload.password,
      username: payload.username,
      email: payload.email,
      role: payload.roleSelect,
    };
    await HttpClient.post('/admin/master', roleInfo);
    const info = {
      page: 1,
      page_size: 10,
      expand: 'role',
    };
    const url = `/admin/master?${HttpClient.encodeParams(info)}`;
    const accountListRep = await HttpClient.get(url);
    dispatch(updateAccountList(accountListRep.data.data));
  };
}

export function disableAccount(payload) {
  return async (dispatch, getState) => {
    const {accountList} = getState();
    const accountRep = await HttpClient.put(
      `/admin/master/${payload.id}`,
      payload,
    );
    accountList.results = accountList.results.map(val =>
      val.id === accountRep.data.data.id
        ? {...val, is_active: accountRep.data.data.is_active}
        : val,
    );
    dispatch(updateAccountList(accountList));
  };
}

export function delAccount(payload) {
  return async dispatch => {
    await HttpClient.delete(`/admin/master/${payload.id}`);
    const info = {
      page: 1,
      page_size: 10,
      expand: 'role',
    };
    const url = `/admin/master?${HttpClient.encodeParams(info)}`;
    const accountListRep = await HttpClient.get(url);
    dispatch(updateAccountList(accountListRep.data.data));
  };
}

export function loadAccountDetail(payload) {
  return async (dispatch, getState) => {
    const {accountList} = getState();
    const roleInfo = accountList.roleList.find(
      item => item.id === payload.role.id,
    );
    payload.role = roleInfo;
    dispatch(updateAccountDetail(payload));
  };
}

export function updateAccount(payload) {
  return async (dispatch, getState) => {
    const {accountDetail} = getState();
    const accountInfo = {
      password: payload.password,
    };
    const accountRep = await HttpClient.put(
      `/admin/master/${accountDetail.id}`,
      accountInfo,
    );
    accountDetail.password = accountRep.data.data.password;
    dispatch(updateAccountDetail(accountDetail));
  };
}
